<?php

/**
 * Description of Util
\* www.teuker.nl - mail@teuker.nl
 * 
 * @author francisc
 */
class Util {
    const RESERVATION_NEW_TODAY = 1;
    const RESERVATION_CANCELATION_TODAY = 2;
    const RESERVATION_NEW_GROUP_TODAY = 3;
    const RESERVATION_CANCELATION_GROUP_TODAY = 4;
    const RESERVATION_NEW_WITH_REMAKRS = 5;

    const TYPE_STRING_NEW_TODAY = 'new_today';
    const TYPE_STRING_CANCELLED_TODAY = 'cancelled_today';
    const TYPE_STRING_NEW_GROUP_TODAY = 'new_group_today';
    const TYPE_STRING_CANCELLED_GROUP_TODAY = 'cancelled_group_today';
    const TYPE_STRING_NEW_WITH_REMARKS = 'new_with_remarks';

/*********************************************************************************/
    public static function loadI18NHelper() {
        sfContext::getInstance()->getConfiguration()->loadHelpers('I18N');
    }

/*********************************************************************************/
    public static function getAllDaysIntervals($restaurant_id) {
        $day_intervals = array();
        for ($i = 1; $i <= 7; $i++) {
            $day_intervals[$i] = SqlEngine::getDayIntervalsInfo(array('day' => $i, 'restaurant_id' => $restaurant_id));
        }

        return $day_intervals;
    }

/*********************************************************************************/
    public static function convertDateServerClient($date, $locale = "nl") {
        Util::loadHelper('Date');
        switch ($locale) {
            case "en":
                $date = format_date($date, 'MM/dd/yyyy');
                break;
            default:
                $date = format_date($date, 'dd/MM/yyyy');
                break;
        }

        return $date;
    }

/********************************************************************************/
    public static function convertDateClientServer($date, $locale = "nl") {
        if ('' == $date || null == $date)
            return null;

        switch ($locale) {
            case "en":
            case "nl":
                $separator = "/";
                break;
            default:
                $separator = "-";
                break;
        }

        $date_info = explode($separator, $date);

        if (3 !== count($date_info))
            return null;

        switch ($locale) {
            case "en":
                $day = $date_info[1];
                $month = $date_info[0];
                $year = $date_info[2];
                break;
            case "nl":
                $day = $date_info[0];
                $month = $date_info[1];
                $year = $date_info[2];
                break;
            default: /* defaults to EN */
                $day = $date_info[1];
                $month = $date_info[0];
                $year = $date_info[2];
                break;
        }

        $date_for_server = $year . '-' . $month . '-' . $day;

        return $date_for_server;
    }

/*********************************************************************************/
    public static function getDate($flag = null) {
        if ('today' == $flag)
            return date('y-m-d');

        return date('d-m-y');
    }

/*********************************************************************************/
    public static function isToday($date) {

        return date('Y-m-d') == $date;
    }

    public static function isTomorrow($date) {
        $tomorrow = date('Y-m-d', mktime(0,0,0,date('m'), date('d') + 1, date('Y')));

        return $date == $tomorrow;
    }

/*********************************************************************************/
    //FIXME -> it works now, guess this is obsolete... : Check date sunday
    public static function offsetTodayDate($date, $day_offset) {
        
        return date('Y-m-d', mktime(0,0,0,date('m'), date('d') + $day_offset, date('Y')));
    }

/*********************************************************************************/
    public static function getDayText($date) {
        
        return date('l', Util::dateToTimestamp($date));
    }

/*********************************************************************************/
    public static function decideDayIndex($date) {

        return $dw = date("w", Util::dateToTimestamp($date));
    }

/*********************************************************************************/
    public static function getShortDate($date) {
        $date_timestamp = Util::dateToTimestamp($date);

        $date = date("D", $date_timestamp) . ' ' . date("d", $date_timestamp) . ' ' . date("M", $date_timestamp);
        
        $date = str_replace('Mon', 'Ma', $date);
        $date = str_replace('Tue', 'Di', $date);
        $date = str_replace('Wed', 'Wo', $date);
        $date = str_replace('Thu', 'Do', $date);
        $date = str_replace('Fri', 'Vr', $date);
        $date = str_replace('Sat', 'Za', $date);
        $date = str_replace('Sun', 'Zo', $date);
        
        return $date;
    }

/*********************************************************************************/
    public static function dateToTimestamp($date) {
        list($year, $month, $day) = explode('-', $date);
        
        return mktime(0, 0, 0, $month, $day, $year);
    }

/*********************************************************************************/
    public static function loadHelper($helper) {
        sfContext::getInstance()->getConfiguration()->loadHelpers($helper);
    }

/*********************************************************************************/
    public static function decide_message_type($message) {
        $user = sfContext::getInstance()->getUser();

        if (!empty($message['comments_diet']) || !empty($message['comments_internal']))
            return Util::RESERVATION_NEW_WITH_REMAKRS;

        if (date('Y-m-d') == $message['date'] && $message['person_no'] > 10 && empty($message['deleted_at']))
            return Util::RESERVATION_NEW_GROUP_TODAY;
            // FIXME: 10 is hard coded, it's a setting per restaurant

        if (date('Y-m-d') == $message['date'] && $message['person_no'] > 10 && !empty($message['deleted_at']))
            return Util::RESERVATION_CANCELATION_GROUP_TODAY;
            // FIXME: 10 is hard coded, it's a setting per restaurant
        
        if (date('Y-m-d') == $message['date'] && empty($message['deleted_at']))
            return Util::RESERVATION_NEW_TODAY;

        if (date('Y-m-d') == $message['date'] && !empty($message['deleted_at']))
            return Util::RESERVATION_CANCELATION_TODAY;
    }

/*********************************************************************************/
    public static function is_group_reservation($person_no) {
        $restaurant_id = sfContext::getInstance()->getUser()->getAttribute('current_restaurant_id');
        
        if (null == $restaurant_id)
            return false;
        
        $settings = SqlEngine::getSettings(array('restaurant_id' => $restaurant_id));

        if ($person_no >= $settings['group_size'])
            return true;

        return false;
    }

/*********************************************************************************/
    public static function retrieve_cookie_array($cookie) {
        
        return get_magic_quotes_gpc() ? unserialize(stripslashes($cookie)) : unserialize($cookie);
    }
    
/*********************************************************************************/
    public static function init_mailer() {
        $mailer = sfContext::getInstance()->getMailer();
        $user = sfContext::getInstance()->getUser();
        
        $mailer->getRealtimeTransport()->setUsername($user->getAttribute('restaurant_email_backup'));
        $mailer->getRealtimeTransport()->setPassword($user->getAttribute('restaurant_email_backup_password'));
        
        return $mailer;
    }
    
/*********************************************************************************/
    public static function getTemplate($type, $category) {
        $template_types = SqlEngine::getTemplateTypes(array('name' => $type));
        $template_category = SqlEngine::getTemplateCategory(array('name' => $category));
        
        $template = SqlEngine::getTemplates(array('category_id' => $template_category[0]['template_category_id'],
                                                  'type_id' => $template_types[0]['template_type_id']));
        
        return $template[0];
    }
    
/*********************************************************************************
 * 
 * 	THANK YOU EMAIL
 * 
 */
    
    public static function send_thank_you_email($form_data, $token, $reservationId) {
        Util::loadHelper('Partial');
        Util::loadHelper('I18N');
        $user = sfContext::getInstance()->getUser();
        $mailer = Util::init_mailer();
        
        $template = Util::getTemplate('email', 'thankyou');
        $body = $template['body'];
        
        /* process  G U E S T   body */
        $salutation = get_partial('email/full_salutation', array('salutation' => $form_data->getValue('salutation'),
                                                           'name_first' => $form_data->getValue('name_first'),
                                                           'name_last' => $form_data->getValue('name_last')));
        
        $reservation_date_time = get_partial('email/thank_you_reservation_summary', 
                                    array('date' => $form_data->getValue('date'),
                                          'time' => $form_data->getValue('time_hour') . ':' . $form_data->getValue('time_minute'),
                                          'person_no' => $form_data->getValue('person_no')));
        
        $remark = get_partial('email/remark', array('diet' => $form_data->getValue('comments_diet')));
        
        $group_menu = '';
        if (null != $form_data->getValue('menu_id')) {
            $menu = SqlEngine::getMenus(array('menu_id' => $form_data->getValue('menu_id')));
            $group_menu = get_partial('email/group_menu');
            $group_menu = str_replace('##group_menu##', $menu[0]['name'], $group_menu);
            $group_menu = str_replace('##group_menu_description##', $menu[0]['description'], $group_menu);
        }
        
        $deep_link = "http://{$_SERVER['HTTP_HOST']}/show/" . $token;

        $body = str_replace('##salutation##', $salutation, $body);
        $body = str_replace('##reservation_time_date##', $reservation_date_time, $body);
        $body = str_replace('##remark##', $remark, $body);
        $body = str_replace('##deep_link_reservation##', $deep_link, $body);
        $body = str_replace('##group##', $group_menu, $body);
        
        /* attach the header and the footer */
        $body = $user->getAttribute('restaurant_email_header') . $body . $user->getAttribute('restaurant_email_footer');

        /* send confirmation email to the user */
        $message = $mailer->compose(array('office@dudok.nl' => $user->getAttribute('restaurant_email_from')),
                                          $form_data->getValue('email'),
                                          $template['subject'],
                                          $body);
        $message->setContentType('text/html');
        $mailer->send($message);
        
        /* send backup email to the restaurant email address */
        $subject = $user->getAttribute('restaurant_name') . ' ' . Util::convertDateServerClient($form_data->getValue('date'))
                        . ' ' . $form_data->getValue('time_hour') . ':' . $form_data->getValue('time_minute')
                        . ' - ' . __('New reservation') . ' - ' . $form_data->getValue('name_last')
                        . ', ' . $form_data->getValue('person_no') . ' ' . __('persons');
        
        $message = $mailer->compose(array('office@dudok.nl' => 'dudok.nl'),
                                          $user->getAttribute('restaurant_email_backup'),
                                          $subject,
                                          $body);

        $message->setContentType('text/html');
        $mailer->send($message);
        
        /* update the reservation log */
        $message = __('confirmation sent to') . ': ' . $form_data->getValue('email'). $subject . '.' ;
        SqlEngineCore::get()->insert(array('table' => 'reservation_log',
                                           'columns' => array(
                                               'reservation_id' => $reservationId,
                                               'user_id' => $user->getAttribute('user_id'),
                                               'message' => $message,
                                               'created_at' => 'NOW()')));
        
        /*******************************************************************************
         * 	send email to the   M A N A G E R   on group menu or diet/internal comments 
         * *****************************************************************************/
        
        $hasgroup_b = ( $form_data->getValue('person_no') >= $user->getAttribute('group_size') ? 1 : 0 );
        $hasremark_b = (null != $form_data->getValue('comments_diet') ? 1 : 0 );
        $hasinternal_b = (null != $form_data->getValue('comments_internal') ? 1 : 0 );
        
        
        if ( $hasgroup_b + $hasinternal_b + $hasremark_b > 0 ) {
        	
        	$template = Util::getTemplate('email', 'manager new');
        	$body = $template['body'];
        	$reservation_date_time = get_partial('email/thank_you_reservation_summary', 
                                    array('date' => $form_data->getValue('date'),
                                          'time' => $form_data->getValue('time_hour') . ':' . $form_data->getValue('time_minute'),
                                          'person_no' => $form_data->getValue('person_no')));
        
	        
            $remark = '-- ' . __('no remarks') . ' --';
            if ($hasremark_b) {
            	$remark = $form_data->getValue('comments_diet');
            }
            
	        $internal = '-- ' . __('no remarks') . ' --';
	        if ($hasinternal_b) {
	        	$internal = $form_data->getValue('comments_internal');
	        }
	        
	        $group_menu = '';
	        if ($hasgroup_b) {
	            $menu = SqlEngine::getMenus(array('menu_id' => $form_data->getValue('menu_id')));
	            $group_menu = get_partial('email/group_menu');
	            $group_menu = str_replace('##group_menu##', $menu[0]['name'], $group_menu);
	            $group_menu = str_replace('##group_menu_description##', $menu[0]['description'], $group_menu);
	        }
	        
	        $deep_link = "http://{$_SERVER['HTTP_HOST']}/show/" . $token;
	
	        $guesttel = '';
	        	$guesttel .= ( null != $form_data->getValue('phone') ? '<strong>t.</strong> ' . $form_data->getValue('phone') . '<br />' : '' );
	        	$guesttel .= ( null != $form_data->getValue('mobile') ? '<strong>m.</strong> ' . $form_data->getValue('mobile') . '<br />' : '' );
	        	
	        $body = str_replace('##salutation##', $salutation, $body);
	        $body = str_replace('##reservation_time_date##', $reservation_date_time, $body);
	        $body = str_replace('##remark##', $remark, $body);
	        $body = str_replace('##internal##', $internal, $body);
	        $body = str_replace('##deep_link_reservation##', $deep_link, $body);
	        $body = str_replace('##group##', $group_menu, $body);
	        $body = str_replace('##date##', Util::convertDateServerClient($form_data->getValue('date')), $body);
	        $body = str_replace('##time##', $form_data->getValue('time_hour') . ':' . $form_data->getValue('time_minute'), $body);
	        $body = str_replace('##guestname##', $form_data->getValue('name_last'), $body);
			$body = str_replace('##guesttel##', $guesttel, $body);
	        $body = str_replace('##guestaddress##', $form_data->getValue('address'), $body);
	        $body = str_replace('##persons##', $form_data->getValue('person_no'), $body);
	        
	        
	        $subject = $template['subject'];
	        $subject = str_replace('##date##', Util::convertDateServerClient($form_data->getValue('date')), $subject);
	        $subject = str_replace('##time##', $form_data->getValue('time_hour') . ':' . $form_data->getValue('time_minute'), $subject);
	        $subject = str_replace('##guestname##', $form_data->getValue('name_last'), $subject);
			$subject = str_replace('##guesttel##', $guesttel, $subject);
	        $subject = str_replace('##guestaddress##', $form_data->getValue('address'), $subject);
	        $subject = str_replace('##persons##', $form_data->getValue('person_no'), $subject);
	        
	        $message = $mailer->compose(array('office@dudok.nl' => 'dudok.nl'),
	                                          $user->getAttribute('restaurant_email_manager'),
	                                          $subject,
	                                          $body);
	
	        $message->setContentType('text/html');
	        $mailer->send($message);
	        
	        /* update the reservation log */
	        $message = __('manager notice sent to') . ': ' . $user->getAttribute('restaurant_email_manager'). ' - ' . $subject . '.' ;
	        SqlEngineCore::get()->insert(array('table' => 'reservation_log',
	                                           'columns' => array(
	                                               'reservation_id' => $reservationId,
	                                               'user_id' => $user->getAttribute('user_id'),
	                                               'message' => $message,
	                                               'created_at' => 'NOW()')));
        }
        
        
        
        
    }
    
/*********************************************************************************
 * 
 * 	UPDATE EMAIL
 * 
 */
    public static function send_update_email($reservation) {
        Util::loadHelper('Partial');
        Util::loadHelper('I18N');
        $user = sfContext::getInstance()->getUser();
        $mailer = Util::init_mailer();
        
        $template = Util::getTemplate('email', 'changed');
        
        /* prep body */
        $body = $template['body'];
        $deep_link = "http://{$_SERVER['HTTP_HOST']}/show/" . $reservation['token'];
        
        $salutation = get_partial('email/full_salutation', array('salutation' => $reservation['salutation'],
                                                           'name_first' => $reservation['name_first'],
                                                           'name_last' => $reservation['name_last']));
        
        $reservation_date_time = get_partial('email/thank_you_reservation_summary', 
                                    array('date' => $reservation['date'],
                                          'time' => $reservation['time'],
                                          'person_no' => $reservation['person_no']));
        
        /* process body */
        $body = str_replace('##salutation##', $salutation, $body);
        $body = str_replace('##deep_link_reservation##', $deep_link, $body);
        $body = str_replace('##reservation_time_date##', $reservation_date_time, $body);
        
        /* attach the header and the footer */
        $body = $user->getAttribute('restaurant_email_header') . $body . $user->getAttribute('restaurant_email_footer');
        
        
         /* send update confirmation email to the user */
        $message = $mailer->compose(array('office@dudok.nl' => $user->getAttribute('restaurant_email_from')), 
        
                                    $reservation['email'], 
                                    $template['subject'], 
                                    $body);
                
        
        $message->setContentType('text/html');
        $mailer->send($message);
        
        /* send backup email to the restaurant email address */
        $subject = $user->getAttribute('restaurant_name') . ' ' . Util::convertDateServerClient($reservation['date'])
                        . ' ' . $reservation['time']
                        . ' - ' . __('Changed reservation') . ' - ' . $reservation['name_last']
                        . ', ' . $reservation['person_no'] . ' ' . __('persons');
        
        $message = $mailer->compose(array('sebastiaan@dudok.nl' => $user->getAttribute('restaurant_email_from')),
                                          $user->getAttribute('restaurant_email_backup') . '',
                                          $subject,
                                          $body);

        $message->setContentType('text/html');
        $mailer->send($message);
        
        /* update the reservation log */
        $message = __('sent updated reservation mail') . ':  ' .  $form_data->getValue('email'). ': ' . $subject . '.' ;
        SqlEngineCore::get()->insert(array('table' => 'reservation_log',
                                           'columns' => array(
                                               'reservation_id' => $reservationId,
                                               'user_id' => $user->getAttribute('user_id'),
                                               'message' => $message,
                                               'created_at' => 'NOW()')));
        
        
    	/*******************************************************************************
         * 	send email to the   M A N A G E R   on group menu or diet/internal comments 
         * *****************************************************************************/
        
        $hasgroup_b = ( $form_data->getValue('person_no') >= $user->getAttribute('group_size') ? 1 : 0 );
        $hasremark_b = (null != $form_data->getValue('comments_diet') ? 1 : 0 );
        $hasinternal_b = (null != $form_data->getValue('comments_internal') ? 1 : 0 );
        
        
        if ( $hasgroup_b + $hasinternal_b + $hasremark_b > 0 ) {
        	
        	$template = Util::getTemplate('email', 'manager change');
        	$body = $template['body'];
        	$reservation_date_time = get_partial('email/thank_you_reservation_summary', 
                                    array('date' => $form_data->getValue('date'),
                                          'time' => $form_data->getValue('time_hour') . ':' . $form_data->getValue('time_minute'),
                                          'person_no' => $form_data->getValue('person_no')));
        
	        
            $remark = '-- ' . __('no remarks') . ' --';
            if ($hasremark_b) {
            	$remark = $form_data->getValue('comments_diet');
            }
            
	        $internal = '-- ' . __('no remarks') . ' --';
	        if ($hasinternal_b) {
	        	$internal = $form_data->getValue('comments_internal');
	        }
	        
	        $group_menu = '';
	        if ($hasgroup_b) {
	            $menu = SqlEngine::getMenus(array('menu_id' => $form_data->getValue('menu_id')));
	            $group_menu = get_partial('email/group_menu');
	            $group_menu = str_replace('##group_menu##', $menu[0]['name'], $group_menu);
	            $group_menu = str_replace('##group_menu_description##', $menu[0]['description'], $group_menu);
	        }
	        
	        $deep_link = "http://{$_SERVER['HTTP_HOST']}/show/" . $token;
	
	        $guesttel = '';
	        	$guesttel .= ( null != $form_data->getValue('phone') ? '<strong>t.</strong> ' . $form_data->getValue('phone') . '<br />' : '' );
	        	$guesttel .= ( null != $form_data->getValue('mobile') ? '<strong>m.</strong> ' . $form_data->getValue('mobile') . '<br />' : '' );
	        	
	        $body = str_replace('##salutation##', $salutation, $body);
	        $body = str_replace('##reservation_time_date##', $reservation_date_time, $body);
	        $body = str_replace('##remark##', $remark, $body);
	        $body = str_replace('##internal##', $internal, $body);
	        $body = str_replace('##deep_link_reservation##', $deep_link, $body);
	        $body = str_replace('##group##', $group_menu, $body);
	        $body = str_replace('##date##', Util::convertDateServerClient($form_data->getValue('date')), $body);
	        $body = str_replace('##time##', $form_data->getValue('time_hour') . ':' . $form_data->getValue('time_minute'), $body);
	        $body = str_replace('##guestname##', $form_data->getValue('name_last'), $body);
			$body = str_replace('##guesttel##', $guesttel, $body);
	        $body = str_replace('##guestaddress##', $form_data->getValue('address'), $body);
	        $body = str_replace('##persons##', $form_data->getValue('person_no'), $body);
	        
	        
	        $subject = $template['subject'];
	        $subject = str_replace('##date##', Util::convertDateServerClient($form_data->getValue('date')), $subject);
	        $subject = str_replace('##time##', $form_data->getValue('time_hour') . ':' . $form_data->getValue('time_minute'), $subject);
	        $subject = str_replace('##guestname##', $form_data->getValue('name_last'), $subject);
			$subject = str_replace('##guesttel##', $guesttel, $subject);
	        $subject = str_replace('##guestaddress##', $form_data->getValue('address'), $subject);
	        $subject = str_replace('##persons##', $form_data->getValue('person_no'), $subject);
	        
	        $message = $mailer->compose(array('office@dudok.nl' => 'dudok.nl'),
	                                          $user->getAttribute('restaurant_email_manager'),
	                                          $subject,
	                                          $body);
	
	        $message->setContentType('text/html');
	        $mailer->send($message);
	        
	        /* update the reservation log */
	        $message = __('updated reservation notice sent') . ' - ' . $subject . ': ' . $user->getAttribute('restaurant_email_manager');
	        SqlEngineCore::get()->insert(array('table' => 'reservation_log',
	                                           'columns' => array(
	                                               'reservation_id' => $reservationId,
	                                               'user_id' => $user->getAttribute('user_id'),
	                                               'message' => $message,
	                                               'created_at' => 'NOW()')));
        }
    }
    
/*********************************************************************************
 * 
 * 
 * 		CANCELLED RESERVATION EMAILS
 * 
 * 
 **********************************************************************************/
    
    
    public static function send_cancellation_email($reservation) {
    	

        Util::loadHelper('Partial');
        Util::loadHelper('I18N');
        $mailer = sfContext::getInstance()->getMailer();
        $user = sfContext::getInstance()->getUser();
        
        $template = Util::getTemplate('email', 'cancelled');   
        $body = $template['body'];
        $deep_link = "http://{$_SERVER['HTTP_HOST']}/show/" . $reservation['token'];
        
        $salutation = get_partial('email/full_salutation', array('salutation' => $reservation['salutation'],
                                                           'name_first' => $reservation['name_first'],
                                                           'name_last' => $reservation['name_last']));
        
        $reservation_date_time = get_partial('email/thank_you_reservation_summary', 
                                    array('date' => $reservation['date'],
                                          'time' => $reservation['time'],
                                          'person_no' => $reservation['person_no']));
        
        /* process body */
        $body = str_replace('##salutation##', $salutation, $body);
        $body = str_replace('##deep_link_reservation##', $deep_link, $body);
        $body = str_replace('##reservation_time_date##', $reservation_date_time, $body);
        
        /* attach the header and the footer */
        $body = $user->getAttribute('restaurant_email_header') . $body . $user->getAttribute('restaurant_email_footer');
        
        
        /* send email to the guest email address */
        $subject = $user->getAttribute('restaurant_name') . ' ' . Util::convertDateServerClient($reservation['date'])
                        . ' ' . $reservation['time']
                        . ' - ' . __('Cancelled reservation') . ' - ' . $reservation['name_last']
                        . ', ' . $reservation['person_no'] . ' ' . __('persons');
        
        $message = $mailer->compose(array('office@dudok.nl' => $user->getAttribute('restaurant_email_from')),
                                          $reservation['email'],
                                          $subject,
                                          $body);

        $message->setContentType('text/html');
        $mailer->send($message);
        
        
        /* send backup email to the restaurant email address */
        $subject = $user->getAttribute('restaurant_name') . ' ' . Util::convertDateServerClient($reservation['date'])
                        . ' ' . $reservation['time']
                        . ' - ' . __('Cancelled reservation') . ' - ' . $reservation['name_last']
                        . ', ' . $reservation['person_no'] . ' ' . __('persons');
        
        $message = $mailer->compose(array('office@dudok.nl' => $user->getAttribute('restaurant_email_from')),
                                          $user->getAttribute('restaurant_email_backup') . '',
                                          $subject,
                                          $body);

        $message->setContentType('text/html');
        $mailer->send($message);
        
        
        
    }
    
/*********************************************************************************/
    public static function is_seat_limit($person_no, $date, $time_hour, $time_minute, $user) {
        $restaurant_id = $user->getAttribute('current_restaurant_id');

        if (null == $date)
            return false;
        
        /* this should not happen */
        if (null == $restaurant_id)
            return sfView::NONE;
        
        $day_of_the_week = date('N', strtotime($date));
        $full_time = $time_hour . ':' . $time_minute;
        
        $intervals = SqlEngine::getDayIntervalsInfo(array('day' => $day_of_the_week,
                                                          'restaurant_id' => $restaurant_id,
                                                          'time' => $full_time));
		//var_dump($intervals);
        if (empty($intervals))
            return false;

        $seat_limit = $intervals[0]['seats'];

        /* get the total seats already reserved */
        $already_taken_seats = 0;
        $reservations = SqlEngine::getReservations(array('restaurant_id' => $restaurant_id,
                                                         'date' => $date,
                                                         'time_between' => array($intervals[0]['time_start'], $intervals[0]['time_end'])));
        foreach ($reservations as $reservation)
            $already_taken_seats += $reservation['person_no'];
        
        if ($already_taken_seats + $person_no > $seat_limit)
            return true;
        
        return false;
    }
    
/*********************************************************************************/
    public static function is_block_time($date, $time_hour, $time_minute, $user) {
        $full_time = $time_hour . ':' . $time_minute;

        $restaurant_id = $user->getAttribute('current_restaurant_id');

        if (null == $restaurant_id || null == $date)
            return false;

        $blocked_times = SqlEngine::getBlockTimes(array('restaurant_id' => $restaurant_id,
                                                        'date' => $date,
                                                        'time' => $full_time));
        
        if (0 == count($blocked_times))
            return array('is_block_time' => false);
        
        return array('is_block_time' => true, 'reason' => $blocked_times[0]['reason']);
        
//        if (0 == count($blocked_times))
//            return false;
//        
//        return true;
    }
    
/*********************************************************************************/
    public static function set_session_info($restaurant, $settings, $user) {
        $user->setAttribute('current_restaurant_id', $restaurant['restaurant_id']);
        
        $user->setAttribute('restaurant_web',          $settings['web']);
        $user->setAttribute('group_size',              $settings['group_size']);
        $user->setAttribute('restaurant_name',         $restaurant['name']);
        $user->setAttribute('restaurant_phone',        $settings['phone']);
        $user->setAttribute('restaurant_email_header', $settings['email_header']);
        $user->setAttribute('restaurant_email_footer', $settings['email_footer']);
        // HV 19-8
        $user->setAttribute('restaurant_html_header', $settings['header']);
        $user->setAttribute('restaurant_html_footer', $settings['footer']);
        // HV 9-9
        $user->setAttribute('restaurant_email_manager', $settings['email_manager']);
        $user->setAttribute('restaurant_occasions',	$settings['occasions']);
        // --
        $user->setAttribute('restaurant_email_backup', $settings['email_backup']);
        $user->setAttribute('restaurant_email_backup_password', $settings['email_backup_password']);
        $user->setAttribute('restaurant_email_from',   $settings['email_from']);
    }
}
